<script setup>

import {Search} from "@element-plus/icons-vue";
import {ref} from "vue";
import {AddUserGroup, GetSearchUserGroup, GetUserGroup, RemoveUserGroup, UpdateUserGroup} from "@/api/index.js";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
const router = useRouter();
// 通过用户输入的查询数据进行数据查询
const search_classes_name = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
// 数据总数
const total = ref();
// 获取用户组数据
const tableData = ref([]);
// 点击获取所有触发函数
//搜索用户组
const handleGetUserGroup =async (data)=>{
  try {
    const res = await GetUserGroup(data)
    total.value = res.count
    tableData.value = res.results
    tableData.value.sort((a, b) => a.id - b.id);
  } catch (error) {
    console.log(error);
  }
}
const handleGetUserGroupAll = ()=>{
  handleGetUserGroup({
        page: 1,
        size: pageSize.value
      }
  )
}

const handleSearchGroupName = async(data)=>{
  data.name = search_classes_name.value
  try {
    const res =  await GetSearchUserGroup(data)
    total.value = res.count
    tableData.value = res.results
  } catch (error) {
    ElMessage.error("获取失败，请重新登录");
    await router.push("/login")
  }
}
const handleSearchGroupNameBtn =()=>{
  currentPage.value = 1
  handleSearchGroupName({
    page: 1,
    size: pageSize.value,
  })
}

//分页器
const handleCurrentChange = async (val) => {
  currentPage.value = val;
  await handleGetUserGroup({
        page: val,
        size: pageSize.value
      }
  )};

//添加用户组
const handleAddGroup = ()=>{
  ElMessageBox.prompt('请输入您要添加的组名', '添加用户组', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(async({ value }) => {
        try {
          const res = await AddUserGroup({name:value})
          tableData.value.push(res)
          total.value++
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试添加用户组！')
        }
      })

}

// 修改用户组信息
const handleUpdate = (id)=>{
  ElMessageBox.prompt('请输入您要修改之后组的名称', '修改用户组', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(async({ value }) => {
        try {
          const res = await UpdateUserGroup({name:value,id})
          const index =  tableData.value.findIndex(item=>item.id==id)
          tableData.value[index].name = res.name
          ElMessage.success('用户组信息修改成功！')
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试修改用户组信息！')
        }
      })
}

// 删除用户组信息
const handleDelete = (id)=>{
  ElMessageBox.confirm(
      '确定移除此用户组吗?',
      '移除用户组',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
  )
      .then(async() => {
        try {
          await RemoveUserGroup(id)
          tableData.value = tableData.value.filter(item=>item.id!==id)
          total.value--
          tableData.value.sort((a, b) => a.id - b.id);
          ElMessage.success('用户组信息删除成功！')
        } catch (error) {
          ElMessage.error('网络错误，请稍后尝试删除用户组信息！')
        }
      })

}
handleGetUserGroupAll()
</script>

<template>
  <div class="search">
    <div class="mt-4">
      <el-input v-model="search_classes_name" placeholder="请输入组名..." class="input-with-select">
        <template #prepend >
          <el-button  @click="handleGetUserGroupAll" >获取所有</el-button>
        </template>
        <template #append>
          <el-button :icon="Search" @click="handleSearchGroupNameBtn" />
        </template>
      </el-input>
    </div>
  </div>
  <div class="add">
    <el-button type="primary" @click="handleAddGroup">添加组</el-button>
  </div>
  <div class="list">
    <el-table :data="tableData" style="width: 850px">
      <el-table-column label="ID" width="120" header-align="center">
        <template #default="scope">
          <span style="margin-left: 40%">{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="组名称" width="120" header-align="center">
        <template #default="scope">
          <span style="margin-left: 30%">{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" header-align="center">
        <template #default="scope" >
          <div style="margin-left: 40%" >
            <el-button size="small" type="danger" @click="handleUpdate(scope.row.id)">修改</el-button>

            <el-button size="small" type="info" @click="handleDelete(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="pagination" v-if="total > 0">
    <el-pagination background @current-change="handleCurrentChange" :page-size="pageSize" layout="prev, pager, next" :total="total"
                   class="mt-4" :current-page="currentPage" />
  </div>
</template>

<style scoped lang="less">
.search {
  width: 100%;

  .mt-4 {
    width: 800px;
    margin: 50px auto;
  }

  .el-input {
    width: 850px;
    margin: auto;
  }
}
.list {
  width: 100%;

  .el-table {
    margin: 20px auto;
  }
}
.pagination {
  width: 100%;

  .el-pagination {
    width: 200px;
    margin: 20px auto;
  }
}
.add {
  width: 100%;
  display: flex;
  justify-content: flex-end;

  .el-button {
    margin-right: 400px;
  }
}

</style>